package com.tensquare.article.controller;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.service.CommentService;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
@CrossOrigin
public class CommentComtroller {

  @Autowired private CommentService commentService;

  @Autowired private RedisTemplate redisTemplate;

  /**
   * 查询所有评论
   * @return List类型评论集合
   */
  @RequestMapping(method = RequestMethod.GET)
  public Result findAll() {
    List<Comment> list = commentService.findAll();
    return new Result(true, StatusCode.OK, "查询成功", list);
  }

  /**
   * 根据ID查询评论
   * @param id
   * @return
   */
  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  public Result findById(@PathVariable String id) {
    Comment comment = commentService.findById(id);
    return new Result(true, StatusCode.OK, "查询成功", comment);
  }

  /**
   * 新增评论
   * @param comment
   * @return
   */
  @RequestMapping(method = RequestMethod.POST)
  public Result save(@RequestBody Comment comment) {
    commentService.save(comment);
    return new Result(true, StatusCode.OK, "新增成功");
  }

  /**
   * 修改评论
   * @param id
   * @param comment
   * @return
   */
  @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
  public Result update(@PathVariable String id, @RequestBody Comment comment) {
    comment.set_id(id);
    commentService.update(comment);
    return new Result(true, StatusCode.OK, "修改成功");
  }

  /**
   * 删除评论
   * @param id
   * @return
   */
  @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  public Result deleteById(@PathVariable String id) {
    commentService.deleteById(id);
    return new Result(true, StatusCode.OK, "删除成功");
  }

  /**
   * 根据文章id查询评论列表
   * @param articleId 文章id
   * @return 评论列表
   */
  @RequestMapping(value = "/article/{articleId}", method = RequestMethod.GET)
  public Result findByArticleId(@PathVariable String articleId) {
    List<Comment> list = commentService.findByArticleId(articleId);
    return new Result(true, StatusCode.OK, "查询成功", list);
  }


  @RequestMapping(value = "/thumbup/{id}", method = RequestMethod.PUT)
  public Result thumbup(@PathVariable String id) {
    // 模拟获取到用户id，jwt鉴权
    String userId = "123";

    Object result = redisTemplate.opsForValue().get("thumbup_" + userId + "_" + id);

    if (result != null) {
      return new Result(true, StatusCode.OK, "不能重复点赞");
    }

    commentService.thumbup(id);
    redisTemplate.opsForValue().set("thumbup_" + userId + "_" + id, 1);
    return new Result(true, StatusCode.OK, "点赞成功");
  }
}
